<!doctype html>



  


<html class="theme-next mist use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="baidu-site-verification" content="zD47G9xe42" />


<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="uiste个人博客网站,uiste,uiste博客,PHP,运维,Hexo,技术博客" />





  <link rel="alternate" href="/atom.xml" title="uiste" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="Stay Hungry，Stay Foolish">
<meta property="og:type" content="website">
<meta property="og:title" content="uiste">
<meta property="og:url" content="http://blog.uiste.com/index.html">
<meta property="og:site_name" content="uiste">
<meta property="og:description" content="Stay Hungry，Stay Foolish">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="uiste">
<meta name="twitter:description" content="Stay Hungry，Stay Foolish">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 0,
      author: '博主'
    }
  };
</script>




  <link rel="canonical" href="http://blog.uiste.com/"/>

  <title>
 
  uiste - Stay Hungry，Stay Foolish 

</title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  



  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?b58b87af012832b8ae35e33bb45b44fa";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>








  
  
    
  

  <div class="container one-collumn sidebar-position-left 
   page-home 
 ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">uiste</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">uiste个人博客</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      

            <li class="menu-item menu-item-search"> <a title="把这个链接拖到你的Chrome收藏夹工具栏中" href='javascript:(function() {
    function c() {
        var e = document.createElement("link");
        e.setAttribute("type", "text/css");
        e.setAttribute("rel", "stylesheet");
        e.setAttribute("href", f);
        e.setAttribute("class", l);
        document.body.appendChild(e)
    }
 
    function h() {
        var e = document.getElementsByClassName(l);
        for (var t = 0; t < e.length; t++) {
            document.body.removeChild(e[t])
        }
    }
 
    function p() {
        var e = document.createElement("div");
        e.setAttribute("class", a);
        document.body.appendChild(e);
        setTimeout(function() {
            document.body.removeChild(e)
        }, 100)
    }
 
    function d(e) {
        return {
            height : e.offsetHeight,
            width : e.offsetWidth
        }
    }
 
    function v(i) {
        var s = d(i);
        return s.height > e && s.height < n && s.width > t && s.width < r
    }
 
    function m(e) {
        var t = e;
        var n = 0;
        while (!!t) {
            n += t.offsetTop;
            t = t.offsetParent
        }
        return n
    }
 
    function g() {
        var e = document.documentElement;
        if (!!window.innerWidth) {
            return window.innerHeight
        } else if (e && !isNaN(e.clientHeight)) {
            return e.clientHeight
        }
        return 0
    }
 
    function y() {
        if (window.pageYOffset) {
            return window.pageYOffset
        }
        return Math.max(document.documentElement.scrollTop, document.body.scrollTop)
    }
 
    function E(e) {
        var t = m(e);
        return t >= w && t <= b + w
    }
 
    function S() {
        var e = document.createElement("audio");
        e.setAttribute("class", l);
        e.src = i;
        e.loop = false;
        e.addEventListener("canplay", function() {
            setTimeout(function() {
                x(k)
            }, 500);
            setTimeout(function() {
                N();
                p();
                for (var e = 0; e < O.length; e++) {
                    T(O[e])
                }
            }, 15500)
        }, true);
        e.addEventListener("ended", function() {
            N();
            h()
        }, true);
        e.innerHTML = " <p>If you are reading this, it is because your browser does not support the audio element. We recommend that you get a new browser.</p> <p>";
        document.body.appendChild(e);
        e.play()
    }
 
    function x(e) {
        e.className += " " + s + " " + o
    }
 
    function T(e) {
        e.className += " " + s + " " + u[Math.floor(Math.random() * u.length)]
    }
 
    function N() {
        var e = document.getElementsByClassName(s);
        var t = new RegExp("\\b" + s + "\\b");
        for (var n = 0; n < e.length; ) {
            e[n].className = e[n].className.replace(t, "")
        }
    }
 
    var e = 30;
    var t = 30;
    var n = 350;
    var r = 350;
    var i = "//s3.amazonaws.com/moovweb-marketing/playground/harlem-shake.mp3";
    var s = "mw-harlem_shake_me";
    var o = "im_first";
    var u = ["im_drunk", "im_baked", "im_trippin", "im_blown"];
    var a = "mw-strobe_light";
    var f = "//s3.amazonaws.com/moovweb-marketing/playground/harlem-shake-style.css";
    var l = "mw_added_css";
    var b = g();
    var w = y();
    var C = document.getElementsByTagName("*");
    var k = null;
    for (var L = 0; L < C.length; L++) {
        var A = C[L];
        if (v(A)) {
            if (E(A)) {
                k = A;
                break
            }
        }
    }
    if (A === null) {
        console.warn("Could not find a node of the right size. Please try a different page.");
        return
    }
    c();
    S();
    var O = [];
    for (var L = 0; L < C.length; L++) {
        var A = C[L];
        if (v(A)) {
            O.push(A)
        }
    }
})()    '>High</a> </li>

    </ul>
  

 
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
   
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            
  <section id="posts" class="posts-expand">
    
      

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                
                <a class="post-title-link" href="/20161106-1.html" itemprop="url">
                  AJAX跨域请求与AJAX浏览器缓存处理
                </a>
              
            
          </h1>
        

        <div class="post-meta">
        
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-11-06T20:22:19+08:00" content="2016-11-06">
              2016-11-06
            </time>
          </span>

          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/20161106-1.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="20161106-1.html" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h1 id="AJAX"><a href="#AJAX" class="headerlink" title="AJAX"></a>AJAX</h1><h2 id="原生post-提交"><a href="#原生post-提交" class="headerlink" title="原生post 提交"></a>原生post 提交</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line">&lt;script type=&quot;text/javascript&quot;&gt;</div><div class="line">window.onload=function()&#123;</div><div class="line">	document.getElementById(&apos;username&apos;).onblur=function()&#123;</div><div class="line">		var username=document.getElementById(&apos;username&apos;).value;</div><div class="line">		username=encodeURIComponent(username);	//字符编码，防止与URL关键字相混淆</div><div class="line">		var req=new XMLHttpRequest();</div><div class="line">		req.open(&apos;post&apos;,&apos;./5-demo.php&apos;);	//创建连接</div><div class="line">		req.onreadystatechange=function()&#123;	//当状态发生变化</div><div class="line">			if(req.readyState==4 &amp;&amp; req.status==200)&#123;</div><div class="line">				var result=req.responseText;	//接受返回的信息</div><div class="line">				alert(result);</div><div class="line">			&#125;</div><div class="line">		&#125;</div><div class="line">		req.setRequestHeader(&apos;Content-Type&apos;,&apos;application/x-www-form-urlencoded&apos;); //设置请求头</div><div class="line">		req.send(&apos;username=&apos;+username);	//post提交数据</div><div class="line">	&#125;</div><div class="line">&#125;</div><div class="line">&lt;/script&gt;</div><div class="line">&lt;input type=&quot;text&quot; name=&quot;&quot; id=&quot;username&quot;&gt;</div></pre></td></tr></table></figure>
<h2 id="解决浏览器缓存"><a href="#解决浏览器缓存" class="headerlink" title="解决浏览器缓存"></a>解决浏览器缓存</h2><ol>
<li>方法一：添加一个随机数，使得URL地址变得唯一<br><code>req.open(&#39;open&#39;,&#39;./1.php?&#39;+Math.random());</code></li>
<li>方法二：告知浏览器不要缓存页面<br><code>header(&quot;Cache-Control:no-cache&quot;);</code><br><code>header(&quot;Pragma:no-cache&quot;);</code></li>
<li>方法三：当浏览器接受到相应的时候，缓存就已经过期<br><code>header(&quot;Expires:-1&quot;);</code></li>
<li>方法四：<br>设置请求头：<code>req.setRequestHeader(&#39;If-Modified-Since&#39;,&#39;0&#39;);</code><br>客户端通过If-Modified-Since头将服务器端最后发过来的页面时间戳发送回去，服务器端通过时间戳判断客户端的页面是否是最新的，如果不是最新的则返回新的内容，如果是最新的，则返回304重定向到客户端缓存中的页面。</li>
</ol>
<h2 id="跨域请求"><a href="#跨域请求" class="headerlink" title="跨域请求"></a>跨域请求</h2><p>背景：浏览器为了安全考虑，不允许跨域请求。<br>同源策略：一个域名下的JS只能请求同一个域名下的文件，不能跨域请求<br>解决方法：</p>
<ol>
<li>HTML标记的src属性没有同源限制<br><code>&lt;script src=&quot;http://www.uiste.com/test.js&quot;&gt;&lt;/script&gt;</code></li>
<li><p>PHP代理</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">文件一：&lt;?php echo file_get_contents(&apos;http://www.uiste.com/test.php&apos;); ?&gt;</div><div class="line">文件二：&lt;script&gt;req.open(&apos;open&apos;,&apos;6-demo.php&apos;)&lt;/script&gt;</div></pre></td></tr></table></figure>
</li>
<li><p>jsonp<br>JSONP是客户端用get的方式传递一个回调函数的名字给服务器，服务器返回拼接好的调用函数字符串给客户端，然后客户端用js生成script标记，用script标记的src属性引入服务器生成的js代码，</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line">PHP文件一：</div><div class="line">$stu = array(&apos;tom&apos;,&apos;berry&apos;);</div><div class="line">$stu = json_encode($stu);</div><div class="line">$fn = $_GET[&apos;fn&apos;];</div><div class="line">echo &quot;$fn($stu)&quot;;</div><div class="line">HTML文件二：</div><div class="line">&lt;script type=&quot;text/javascript&quot;&gt;</div><div class="line">function show(msg)&#123;alert(msg);&#125;</div><div class="line">window.onload=function()&#123;</div><div class="line">	document.getElementById(&apos;btn&apos;).onclick=function()&#123;</div><div class="line">		var script=document.createElement(&apos;script&apos;);</div><div class="line">		script.src=&quot;http://www.uiste.com/test.php?fn=show&quot;;</div><div class="line">		var body=document.getElementByTagName(&apos;body&apos;)[0];</div><div class="line">		body.appendChild(script);</div><div class="line">	&#125;</div><div class="line">&#125;</div><div class="line">&lt;/script&gt;</div><div class="line">&lt;input type=&quot;button&quot; value=&quot;点击&quot; id=&quot;btn&quot;&gt;</div></pre></td></tr></table></figure>
</li>
</ol>

          
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
      

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                
                <a class="post-title-link" href="/20161101-1.html" itemprop="url">
                  Role-Based Access Control
                </a>
              
            
          </h1>
        

        <div class="post-meta">
        
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-11-01T01:00:21+08:00" content="2016-11-01">
              2016-11-01
            </time>
          </span>

          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/20161101-1.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="20161101-1.html" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h1 id="RBAC"><a href="#RBAC" class="headerlink" title="RBAC"></a>RBAC</h1><p>基于角色的访问控制 (Role-Based Access Control)</p>
<h2 id="表设计"><a href="#表设计" class="headerlink" title="表设计"></a>表设计</h2><figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div></pre></td><td class="code"><pre><div class="line">#创建后台管理员表</div><div class="line">DROP TABLE IF EXISTS ugo_admin;</div><div class="line">CREATE TABLE ugo_admin(</div><div class="line">	admin_id TINYINT UNSIGNED auto_increment PRIMARY KEY COMMENT '管理员id' ,</div><div class="line">	admin_name VARCHAR(50) NOT NULL COMMENT '用户名' ,</div><div class="line">	admin_pwd VARCHAR(50) NOT NULL COMMENT '密码' ,</div><div class="line">	admin_role_id TINYINT UNSIGNED NOT NULL COMMENT '角色编号'</div><div class="line">) ENGINE = INNODB charset = utf8 COMMENT '管理员表';</div><div class="line"># 超级管理员测试数据</div><div class="line">insert into ugo_admin values (null,'aa','aa',0);</div><div class="line"></div><div class="line">#创建后台权限表</div><div class="line">DROP TABLE IF EXISTS ugo_authority;</div><div class="line">CREATE TABLE ugo_authority(</div><div class="line">	auth_id INT UNSIGNED auto_increment PRIMARY KEY COMMENT 'auth_id' ,</div><div class="line">	auth_name VARCHAR(50) NOT NULL COMMENT '权限名称' ,</div><div class="line">	auth_pid INT UNSIGNED NOT NULL COMMENT '权限父级id' ,</div><div class="line">	auth_c VARCHAR(50) NULL COMMENT '控制器名' ,</div><div class="line">	auth_a VARCHAR(50) NULL COMMENT '方法名' ,</div><div class="line">	auth_path VARCHAR(50) NULL COMMENT '全路径,格式:父级id-子级id' ,</div><div class="line">	is_show TINYINT NOT NULL DEFAULT 1 COMMENT '是否显示在导航栏上'</div><div class="line">) ENGINE = INNODB charset = utf8 COMMENT '权限表';</div><div class="line"></div><div class="line">#创建后台角色表</div><div class="line">DROP TABLE IF EXISTS ugo_role;</div><div class="line">CREATE TABLE IF NOT EXISTS ugo_role(</div><div class="line">	role_id TINYINT UNSIGNED auto_increment PRIMARY KEY COMMENT 'role_id' ,</div><div class="line">	role_name VARCHAR(50) NOT NULL COMMENT '角色名称' ,</div><div class="line">	role_auth_ids VARCHAR(255) NOT NULL COMMENT '角色具有权限id的集合，格式1,2,5' ,</div><div class="line">	role_auth_ac text NOT NULL COMMENT '控制器和方法的组合，格式：控制器-方法名'</div><div class="line">) ENGINE = INNODB charset = utf8 COMMENT '角色表';</div><div class="line"></div><div class="line"># *********************************************************** #</div><div class="line">-- 插入测试数据</div><div class="line">insert into ugo_authority values (1,'商品管理',0,'','',1,1);</div><div class="line">insert into ugo_authority values (2,'会员管理',0,'','',2,1);</div><div class="line">insert into ugo_authority values (3,'权限管理',0,'','',3,1);</div><div class="line"></div><div class="line">insert into ugo_authority values (4,'商品列表',1,'Goods','show','1-4',1);</div><div class="line">insert into ugo_authority values (5,'添加商品',1,'Goods','add','1-5',1);</div><div class="line">insert into ugo_authority values (6,'修改商品',1,'Goods','edit','1-6',0);</div><div class="line">insert into ugo_authority values (7,'删除商品',1,'Goods','del','1-7',0);</div><div class="line"></div><div class="line">insert into ugo_authority values (8,'会员列表',2,'Role','show','2-12',1);</div><div class="line">insert into ugo_authority values (9,'添加会员',2,'Role','add','2-13',1);</div><div class="line">insert into ugo_authority values (10,'修改会员',2,'Role','edit','2-14',0);</div><div class="line">insert into ugo_authority values (11,'删除会员',2,'Role','del','2-15',0);</div><div class="line"></div><div class="line">insert into ugo_authority values (12,'权限列表',3,'Authority','show','3-8',1);</div><div class="line">insert into ugo_authority values (13,'添加权限',3,'Authority','add','3-9',1);</div><div class="line">insert into ugo_authority values (14,'修改权限',3,'Authority','edit','3-10',0);</div><div class="line">insert into ugo_authority values (15,'删除权限',3,'Authority','del','3-11',0);</div><div class="line"></div><div class="line">insert into ugo_role values (1,'经理','1,4,5','Goods-show,Goods-add');</div><div class="line">insert into ugo_role values (2,'主管','1,4','Goods-show');</div><div class="line"></div><div class="line">insert into ugo_admin values (null,'aa','aa',0)</div><div class="line"># *********************************************************** #</div></pre></td></tr></table></figure>
<h2 id="菜单后台"><a href="#菜单后台" class="headerlink" title="菜单后台"></a>菜单后台</h2><figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">menu</span><span class="params">()</span></span>&#123;</div><div class="line">        $admin = session(<span class="string">'admin'</span>);</div><div class="line">        $role_id = $admin[<span class="string">'admin_role_id'</span>];</div><div class="line">        <span class="keyword">if</span> ($role_id==<span class="number">0</span>) &#123; <span class="comment">//超级管理员</span></div><div class="line">            $auth_info1 = M(<span class="string">'authority'</span>)-&gt;where(<span class="string">'auth_pid = 0 and is_show = 1'</span>)-&gt;select();<span class="comment">//父级</span></div><div class="line">            $auth_info2 = M(<span class="string">'authority'</span>)-&gt;where(<span class="string">'auth_pid &gt; 0 and is_show = 1'</span>)-&gt;select();<span class="comment">//子级</span></div><div class="line">        &#125;<span class="keyword">else</span>&#123;</div><div class="line">            $role = M(<span class="string">'role'</span>)-&gt;find($role_id); <span class="comment">//通过管理员角色id找到角色信息</span></div><div class="line">            $role_auth_ids = $role[<span class="string">'role_auth_ids'</span>];<span class="comment">//获取该角色的权限信息</span></div><div class="line">            $auth_info1 = M(<span class="string">'authority'</span>)-&gt;where(<span class="string">"auth_pid = 0 and is_show =1 and auth_id in ($role_auth_ids)"</span>)-&gt;select();</div><div class="line">            $auth_info2 = M(<span class="string">'authority'</span>)-&gt;where(<span class="string">"auth_pid &gt; 0 and is_show =1 and auth_id in ($role_auth_ids)"</span>)-&gt;select();</div><div class="line">        &#125;</div><div class="line">        <span class="keyword">$this</span>-&gt;assign(<span class="string">'menu_list'</span>,<span class="keyword">array</span>(</div><div class="line">                <span class="string">'auth_info1'</span> =&gt; $auth_info1,</div><div class="line">                <span class="string">'auth_info2'</span> =&gt; $auth_info2</div><div class="line">            ));</div><div class="line">    	<span class="keyword">$this</span>-&gt;display();</div><div class="line">    &#125;</div></pre></td></tr></table></figure>
<h2 id="菜单前台"><a href="#菜单前台" class="headerlink" title="菜单前台"></a>菜单前台</h2><figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line">&lt;volist name="menu_list.auth_info1" id="vo1"&gt;</div><div class="line">  &lt;li class="collapse" key="&#123;$i&#125;_&#123;$vo1.auth_c&#125;" name="menu"&gt; &#123;$vo1.auth_name&#125;        </div><div class="line">    &lt;ul style="display: none;"&gt;</div><div class="line">      &lt;volist name="menu_list.auth_info2" id="vo2"&gt;</div><div class="line">        &lt;li class="menu-item"&gt;</div><div class="line">	        &lt;a href="/index.php/Admin/&#123;$vo2.auth_c&#125;/&#123;$vo2.auth_a&#125;" target="main-frame"&gt;&lt;if condition="$vo1.auth_id eq $vo2.auth_pid "&gt;&#123;$vo2.auth_name&#125;&lt;/if&gt;</div><div class="line">	        &lt;/a&gt;</div><div class="line">	    &lt;/li&gt;</div><div class="line">      &lt;/volist&gt;</div><div class="line">    &lt;/ul&gt;</div><div class="line">  &lt;/li&gt;</div><div class="line">&lt;/volist&gt;</div></pre></td></tr></table></figure>
<h2 id="防翻墙与越权访问"><a href="#防翻墙与越权访问" class="headerlink" title="防翻墙与越权访问"></a>防翻墙与越权访问</h2><figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">BaseController</span> <span class="keyword">extends</span> <span class="title">Controller</span></span>&#123;</div><div class="line">	<span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">__construct</span><span class="params">()</span></span>&#123;</div><div class="line">		<span class="keyword">parent</span>::__construct();</div><div class="line">		<span class="keyword">$this</span>-&gt;chenkLogin();</div><div class="line">	&#125;</div><div class="line">	<span class="comment">// 防翻墙</span></div><div class="line">	<span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">chenkLogin</span><span class="params">()</span></span>&#123;</div><div class="line">		<span class="keyword">if</span> (strtoupper(CONTROLLER_NAME)==<span class="string">'LOGIN'</span>) &#123;</div><div class="line">			<span class="keyword">return</span>;</div><div class="line">		&#125;</div><div class="line">		$info = session(<span class="string">'admin'</span>);</div><div class="line">		<span class="keyword">if</span> (!$info) &#123;</div><div class="line">			<span class="keyword">echo</span> <span class="string">'&lt;script type="text/javascript"&gt;'</span>;</div><div class="line">			<span class="keyword">echo</span> <span class="string">"window.location.href='/index.php/Admin/Public/login'"</span>;</div><div class="line">			<span class="keyword">echo</span> <span class="string">'&lt;/script&gt;'</span>;</div><div class="line">			<span class="keyword">exit</span>;</div><div class="line">		&#125;</div><div class="line">		<span class="comment">//放置越权访问</span></div><div class="line">		<span class="keyword">if</span> ($info[<span class="string">'admin_role_id'</span>]==<span class="number">0</span>) &#123;</div><div class="line">			<span class="keyword">return</span>;</div><div class="line">		&#125;</div><div class="line">		<span class="comment">//非管理员验证是否具有访问权限(防止越权方法)</span></div><div class="line">		$allow_controller_array = <span class="keyword">array</span>(<span class="string">'INDEX'</span>);<span class="comment">//所有权限都可以访问Index控制器</span></div><div class="line">		$controller_name = strtoupper(CONTROLLER_NAME);<span class="comment">//将当前控制器名转大写</span></div><div class="line">		<span class="keyword">if</span> (!in_array($controller_name, $allow_controller_array)) &#123;</div><div class="line">			$role = M(<span class="string">'role'</span>)-&gt;find($info[<span class="string">'admin_role_id'</span>]);</div><div class="line">			$allow_auth_ac = $role[<span class="string">'role_auth_ac'</span>];<span class="comment">//当前角色允许的权限</span></div><div class="line">			$now_auth_ac = CONTROLLER_NAME . <span class="string">'-'</span> . ACTION_NAME; <span class="comment">//当前角色访问权限</span></div><div class="line">			<span class="keyword">if</span> (<span class="keyword">FALSE</span> === stripos($allow_auth_ac, $now_auth_ac)) &#123;</div><div class="line">				<span class="keyword">$this</span>-&gt;error(<span class="string">'您没有此访问权限'</span>);</div><div class="line">			&#125;</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
          
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
      

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                
                <a class="post-title-link" href="/20161022-1.html" itemprop="url">
                  ThinkPHP
                </a>
              
            
          </h1>
        

        <div class="post-meta">
        
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-10-22T21:57:01+08:00" content="2016-10-22">
              2016-10-22
            </time>
          </span>

          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/20161022-1.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="20161022-1.html" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <p>在ThinkPHP中阻止系统自动创建目录安全文件，可以在首次运行indexo.php 中添加一个常量的定义<br><code>BUILD_DIR_SECURE = false;</code></p>
<h2 id="路由"><a href="#路由" class="headerlink" title="路由"></a>路由</h2><h4 id="普通路由形式（get）"><a href="#普通路由形式（get）" class="headerlink" title="普通路由形式（get）"></a>普通路由形式（get）</h4><p><code>路由写法：http://域名/入口文件?m=分组名&amp;c=控制器名&amp;a=方法名&amp;参数名1=参数值1&amp;参数名2=参数值2....</code></p>
<h4 id="pathinfo-形式路由（默认形式）"><a href="#pathinfo-形式路由（默认形式）" class="headerlink" title="pathinfo 形式路由（默认形式）"></a>pathinfo 形式路由（默认形式）</h4><p><code>路由形式：http://域名/入口文件/分组名/控制器名/方法名/参数名1/参数值1/参数名2/参数值2...（.html）</code></p>
<h4 id="Rewrite路由形式"><a href="#Rewrite路由形式" class="headerlink" title="Rewrite路由形式"></a>Rewrite路由形式</h4><p><code>路由形式：http://域名/分组名/控制器名/方法名/参数名1/参数值1/参数名2/参数值2...（.html）</code></p>
<blockquote>
<p>与pathinfo相比，这个路由形式少了入口文件</p>
<ol>
<li>[httpd.conf] <code>LoadModule rewrite module molules/mod rewrite.so</code></li>
<li>[httpd-vhosts.conf] <code>AllowOverride all</code></li>
<li>[.htaccess]<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">&gt;&lt;IfModule mod_rewrite.c&gt;</div><div class="line">  Options +FollowSymlinks</div><div class="line">  RewriteEngine On</div><div class="line">  RewriteCond %&#123;REQUEST_FILENAME&#125; !-d</div><div class="line">  RewriteCond %&#123;REQUEST_FILENAME&#125; !-f</div><div class="line">  #apache调用php5模块使用</div><div class="line">  #RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]</div><div class="line">  #fast-cgi模式使用</div><div class="line">  RewriteRule ^(.*)$ index.php?s=$1 [QSA,PT,L]</div><div class="line">&lt;/IfModule&gt;</div></pre></td></tr></table></figure>
</li>
</ol>
</blockquote>
<h4 id="兼容路由形式"><a href="#兼容路由形式" class="headerlink" title="兼容路由形式"></a>兼容路由形式</h4><p><code>路由形式：http://域名/入口文件?s=/分组名/控制器名/方法名/参数名1/参数值1（.html）</code></p>

          
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
      

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                
                <a class="post-title-link" href="/20161018-2.html" itemprop="url">
                  命名空间
                </a>
              
            
          </h1>
        

        <div class="post-meta">
        
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-10-18T23:23:50+08:00" content="2016-10-18">
              2016-10-18
            </time>
          </span>

          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/20161018-2.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="20161018-2.html" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <p>学编程就像学开车，老司机带你装逼，带你飞 …···</p>
<h1 id="命名空间"><a href="#命名空间" class="headerlink" title="命名空间"></a>命名空间</h1><h2 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h2><p>背景：如果一个项目很大，有很多文件，很可能有同名的文件。这时候如果组织这些文件就成了大问题。</p>
<p>命名空间通过<code>namespace</code>声明:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">namespace China;</div><div class="line">function getInfo()&#123;</div><div class="line">    </div><div class="line">&#125;</div><div class="line">namespace USA;</div><div class="line">function getInfo()&#123;</div><div class="line">&#125;</div><div class="line">getInfo();//访问USA的getInfo</div></pre></td></tr></table></figure></p>
<p>命名空间是一种封装事物的方法<br>命名空间用来解决在编写类库或应用程序时创建可重用的代码如类或函数时碰到的两类问题：</p>
<ol>
<li>用户编写的代码与PHP内部的类/函数/常量或第三方类/函数/常量之间的名字冲突。</li>
<li>为很长的标识符名称(通常是为了缓解第一类问题而定义的)创建一个别名（或简短）的名称，提高源代码的可读性。</li>
</ol>
<h2 id="定义命名空间"><a href="#定义命名空间" class="headerlink" title="定义命名空间"></a>定义命名空间</h2><p>受命名空间影响的是：类（包括抽象类和traits）、接口、函数和常量。<br>语法：<code>namespace MyProject</code></p>
<blockquote>
<p>必须在其它所有代码之前声明命名空间，命名空间必须是程序脚本的第一条语句。除了一个以外：declare关键字</p>
</blockquote>
<h2 id="定义子命名空间"><a href="#定义子命名空间" class="headerlink" title="定义子命名空间"></a>定义子命名空间</h2><p>命名空间的名字可以使用分层次的方式定义<br>Example #1 声明分层次的单个命名空间<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">&lt;?php</div><div class="line">namespace MyProject\Sub\Level;</div><div class="line">const CONNECT_OK = 1;</div><div class="line">class Connection &#123; /* ... */ &#125;</div><div class="line">function connect() &#123; /* ... */  &#125;</div><div class="line">?&gt;</div></pre></td></tr></table></figure></p>
<blockquote>
<p>可以使用文件的路径来做命名空间。在自动加载类的时候可以通过命名空间的路径来加载类</p>
</blockquote>
<h2 id="访问空间的三种方法"><a href="#访问空间的三种方法" class="headerlink" title="访问空间的三种方法"></a>访问空间的三种方法</h2><ol>
<li>非限定名称访问</li>
<li>完全限定名称访问</li>
<li>[部分]限定名称访问</li>
</ol>
<h2 id="引入命名空间"><a href="#引入命名空间" class="headerlink" title="引入命名空间"></a>引入命名空间</h2><p>完全限定名称访问不方便书写，可以在当前的命名空间下引入其他的命名空间，然后再使用其他命名空间的元素<br>通过<code>use</code>关键字来引入命名空间</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">namespace China\Shanghai\PuDong;</div><div class="line">function getInfo()&#123;</div><div class="line">    echo &apos;aaa&apos;;</div><div class="line">&#125;</div><div class="line">namespace USA\Washington;</div><div class="line">function getInfo()&#123;</div><div class="line">    echo &apos;bb&apos;;</div><div class="line">&#125;</div><div class="line">use China\Shanghai\PuDong;</div><div class="line">getInfo();  //bb</div><div class="line">PuDong\getInfo(); //aa</div></pre></td></tr></table></figure>
<h2 id="引入类-use"><a href="#引入类-use" class="headerlink" title="引入类(use)"></a>引入类(use)</h2><p> 引入与当前控制器同名的类会报错<br> 解决方法：给类取别名<br> 使用as 关键字给命名空间取别名<br> <figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">use China\Shanghai\PuDong\Person as ChinaPerson;</div><div class="line">$person = new ChinaPerson();</div><div class="line">echo $person-&gt;name;</div></pre></td></tr></table></figure></p>
<blockquote>
<p>引入命名空间和引入类都是用的use,他们的区分就看引入的是不是类，如果不是类就是命名空间</p>
<h2 id="公共的命名空间"><a href="#公共的命名空间" class="headerlink" title="公共的命名空间"></a>公共的命名空间</h2><p>如果一个PHP文件中没有<code>namespace</code>关键字声明，则文件中的元素默认存在于公共的空间下。</p>
<p>在一个页面中，包含另一个文件，不会影响当前页面的命名空间</p>
</blockquote>
<h2 id="命名空间的注意事项"><a href="#命名空间的注意事项" class="headerlink" title="命名空间的注意事项"></a>命名空间的注意事项</h2><ol>
<li>命名空间中可以存放：函数、类、const常量，不能存放define常量。</li>
<li>第一个namespace之前不能有任何代码，header()也不行</li>
<li>包含文件不会改变当前的命名空间</li>
</ol>
<p>##　namespace关键字和<code>__NAMESPACE__</code>常量<br>(PHP 5 &gt;= 5.3.0, PHP 7)<br>PHP支持两种抽象的访问当前命名空间内部元素的方法，<code>__NAMESPACE__</code> 魔术常量和namespace关键字</p>
<p>常量<code>__NAMESPACE__</code>的值是包含当前命名空间名称的字符串。在全局的，不包括在任何命名空间中的代码，它包含一个空的字符串。</p>
<blockquote>
<p><code>__NAMESPACE__</code> 示例, 在命名空间中的代码<br>全局代码</p>
</blockquote>
<p>常量 <code>__NAMESPACE__</code> 在动态创建名称时很有用<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">&lt;?php</div><div class="line">namespace MyProject;</div><div class="line"></div><div class="line">function get($classname)</div><div class="line">&#123;</div><div class="line">    $a = __NAMESPACE__ . &apos;\\&apos; . $classname;</div><div class="line">    return new $a;</div><div class="line">&#125;</div><div class="line">?&gt;</div></pre></td></tr></table></figure></p>
<p>允许通过别名引用或导入外部的完全限定名称，是命名空间的一个重要特征。这有点类似于在类 unix 文件系统中可以创建对其它的文件或目录的符号连接。</p>
<p>所有支持命名空间的PHP版本支持三种别名或导入方式：为类名称使用别名、为接口使用别名或为命名空间名称使用别名。PHP 5.6开始允许导入函数或常量或者为它们设置别名。</p>
<p>在PHP中，别名是通过操作符 use 来实现的. 下面是一个使用所有可能的五种导入方式的例子：</p>
<p>Example #1 使用use操作符导入/使用别名<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div></pre></td><td class="code"><pre><div class="line">&lt;?php</div><div class="line">namespace foo;</div><div class="line">use My\Full\Classname as Another;</div><div class="line"></div><div class="line">// 下面的例子与 use My\Full\NSname as NSname 相同</div><div class="line">use My\Full\NSname;</div><div class="line"></div><div class="line">// 导入一个全局类</div><div class="line">use ArrayObject;</div><div class="line"></div><div class="line">// importing a function (PHP 5.6+)</div><div class="line">use function My\Full\functionName;</div><div class="line"></div><div class="line">// aliasing a function (PHP 5.6+)</div><div class="line">use function My\Full\functionName as func;</div><div class="line"></div><div class="line">// importing a constant (PHP 5.6+)</div><div class="line">use const My\Full\CONSTANT;</div><div class="line"></div><div class="line">$obj = new namespace\Another; // 实例化 foo\Another 对象</div><div class="line">$obj = new Another; // 实例化 My\Full\Classname　对象</div><div class="line">NSname\subns\func(); // 调用函数 My\Full\NSname\subns\func</div><div class="line">$a = new ArrayObject(array(1)); // 实例化 ArrayObject 对象</div><div class="line">// 如果不使用 &quot;use \ArrayObject&quot; ，则实例化一个 foo\ArrayObject 对象</div><div class="line">func(); // calls function My\Full\functionName</div><div class="line">echo CONSTANT; // echoes the value of My\Full\CONSTANT</div><div class="line">?&gt;</div></pre></td></tr></table></figure></p>
<p>通过use操作符导入/使用别名，一行中包含多个use语句<br><code>use My\Full\Classname as Another, My\Full\NSname;</code></p>
<h2 id="名称解析示例"><a href="#名称解析示例" class="headerlink" title="名称解析示例"></a>名称解析示例</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div></pre></td><td class="code"><pre><div class="line">&lt;?php</div><div class="line">namespace A;</div><div class="line">use B\D, C\E as F;</div><div class="line">// 函数调用</div><div class="line">foo();      // 首先尝试调用定义在命名空间&quot;A&quot;中的函数foo()</div><div class="line">            // 再尝试调用全局函数 &quot;foo&quot;</div><div class="line">\foo();     // 调用全局空间函数 &quot;foo&quot; </div><div class="line">my\foo();   // 调用定义在命名空间&quot;A\my&quot;中函数 &quot;foo&quot; </div><div class="line">F();        // 首先尝试调用定义在命名空间&quot;A&quot;中的函数 &quot;F&quot; </div><div class="line">            // 再尝试调用全局函数 &quot;F&quot;</div><div class="line">// 类引用</div><div class="line">new B();    // 创建命名空间 &quot;A&quot; 中定义的类 &quot;B&quot; 的一个对象</div><div class="line">            // 如果未找到，则尝试自动装载类 &quot;A\B&quot;</div><div class="line">new D();    // 使用导入规则，创建命名空间 &quot;B&quot; 中定义的类 &quot;D&quot; 的一个对象</div><div class="line">            // 如果未找到，则尝试自动装载类 &quot;B\D&quot;</div><div class="line">new F();    // 使用导入规则，创建命名空间 &quot;C&quot; 中定义的类 &quot;E&quot; 的一个对象</div><div class="line">            // 如果未找到，则尝试自动装载类 &quot;C\E&quot;</div><div class="line">new \B();   // 创建定义在全局空间中的类 &quot;B&quot; 的一个对象</div><div class="line">            // 如果未发现，则尝试自动装载类 &quot;B&quot;</div><div class="line">new \D();   // 创建定义在全局空间中的类 &quot;D&quot; 的一个对象</div><div class="line">            // 如果未发现，则尝试自动装载类 &quot;D&quot;</div><div class="line">new \F();   // 创建定义在全局空间中的类 &quot;F&quot; 的一个对象</div><div class="line">            // 如果未发现，则尝试自动装载类 &quot;F&quot;</div><div class="line">// 调用另一个命名空间中的静态方法或命名空间函数</div><div class="line">B\foo();    // 调用命名空间 &quot;A\B&quot; 中函数 &quot;foo&quot;</div><div class="line">B::foo();   // 调用命名空间 &quot;A&quot; 中定义的类 &quot;B&quot; 的 &quot;foo&quot; 方法</div><div class="line">            // 如果未找到类 &quot;A\B&quot; ，则尝试自动装载类 &quot;A\B&quot;</div><div class="line">D::foo();   // 使用导入规则，调用命名空间 &quot;B&quot; 中定义的类 &quot;D&quot; 的 &quot;foo&quot; 方法</div><div class="line">            // 如果类 &quot;B\D&quot; 未找到，则尝试自动装载类 &quot;B\D&quot;</div><div class="line">\B\foo();   // 调用命名空间 &quot;B&quot; 中的函数 &quot;foo&quot; </div><div class="line">\B::foo();  // 调用全局空间中的类 &quot;B&quot; 的 &quot;foo&quot; 方法</div><div class="line">            // 如果类 &quot;B&quot; 未找到，则尝试自动装载类 &quot;B&quot;</div><div class="line">// 当前命名空间中的静态方法或函数</div><div class="line">A\B::foo();   // 调用命名空间 &quot;A\A&quot; 中定义的类 &quot;B&quot; 的 &quot;foo&quot; 方法</div><div class="line">              // 如果类 &quot;A\A\B&quot; 未找到，则尝试自动装载类 &quot;A\A\B&quot;</div><div class="line">\A\B::foo();  // 调用命名空间 &quot;A\B&quot; 中定义的类 &quot;B&quot; 的 &quot;foo&quot; 方法</div><div class="line">              // 如果类 &quot;A\B&quot; 未找到，则尝试自动装载类 &quot;A\B&quot;</div><div class="line">?&gt;</div></pre></td></tr></table></figure>
          
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
      

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                
                <a class="post-title-link" href="/20161018-1.html" itemprop="url">
                  反射 | PDO
                </a>
              
            
          </h1>
        

        <div class="post-meta">
        
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-10-18T20:52:51+08:00" content="2016-10-18">
              2016-10-18
            </time>
          </span>

          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/20161018-1.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="20161018-1.html" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h1 id="反射、PDO"><a href="#反射、PDO" class="headerlink" title="反射、PDO"></a>反射、PDO</h1><h2 id="反射"><a href="#反射" class="headerlink" title="反射"></a>反射</h2><p>反射是指获取类、方法、属性、参数、注释等封闭信息的方法。<br>主要用来了解类方法、等内部的代码，反射是通过一系列的类实现的。<br>反射：Reflection</p>
<blockquote>
<p>ReflectionClass 报告类中的信息<br>ReflectionFunction 报告函数的信息<br>RefectionException 报告异常类<br>RefectionMethod 报告方法中的信息</p>
</blockquote>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line"><span class="keyword">echo</span> <span class="string">'&lt;pre&gt;'</span>;</div><div class="line">ReflectionClass::export(<span class="string">'Exception'</span>);</div><div class="line"></div><div class="line">ReflectionClass::export(<span class="string">'stdClass'</span>); <span class="comment">//所有类的父类</span></div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<h2 id="通过反射获取类中的属性、方法、常量"><a href="#通过反射获取类中的属性、方法、常量" class="headerlink" title="通过反射获取类中的属性、方法、常量"></a>通过反射获取类中的属性、方法、常量</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line">class Student&#123;</div><div class="line">	const PI=3.14;</div><div class="line">	private $name;</div><div class="line">	public static $national=&apos;中国&apos;：</div><div class="line">	public function show()&#123;</div><div class="line">		echo &apos;aa&apos;;</div><div class="line">	&#125;</div><div class="line">	public static function test()&#123;</div><div class="line">		echo &apos;bb&apos;;</div><div class="line">	&#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line">//通过反射获取类的信息</div><div class="line">//实例化反射对象</div><div class="line">$reflection new ReflectionClass(&apos;Student&apos;);//反射Student类的信息</div><div class="line">$consts = $reflection-&gt;getConstants();//获取所有常量</div><div class="line">$props = $reflection-&gt;getProperties();//获取所有属性</div><div class="line">$methods = $reflection-&gt;getMethods();//获取所有方法</div></pre></td></tr></table></figure>
<blockquote>
<p>自定义修改的类，方便修改</p>
</blockquote>
<h2 id="通过反射获取代理类的对象"><a href="#通过反射获取代理类的对象" class="headerlink" title="通过反射获取代理类的对象"></a>通过反射获取代理类的对象</h2><p>通过调用反射类的newInstance()对象，返回反射</p>
<p><code>$reflection = new ReflectionClass(&#39;Student&#39;);</code><br><code>$str $reflection-&gt;newInstance();</code>  //返回类的实例</p>
<h2 id="反射可以通过反向代理来调用方法"><a href="#反射可以通过反向代理来调用方法" class="headerlink" title="反射可以通过反向代理来调用方法"></a>反射可以通过<code>反向代理</code>来调用方法</h2><h3 id="正向代理"><a href="#正向代理" class="headerlink" title="正向代理"></a>正向代理</h3><p>在运行过程中，如果感知到代理服务器存在就是正向代理。（比如：从局域网进入到外网）</p>
<h3 id="反向代理"><a href="#反向代理" class="headerlink" title="反向代理"></a>反向代理</h3><p>在运行过程中，不能感受到代理服务器存在。（比如京东、淘宝，服务器的请求分发我们是不知道的）</p>
<ol>
<li>通过ReflectionMethod的invoke()反向调用</li>
<li>如果反向调用的是静态方法，invoke()参数为null<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">Student</span></span>&#123;</div><div class="line">	<span class="keyword">private</span> $name;</div><div class="line">	<span class="keyword">public</span>  __construct($name)&#123;</div><div class="line">		<span class="keyword">$this</span>-&gt;name = $name;</div><div class="line">	&#125;</div><div class="line">	<span class="keyword">public</span>  <span class="function"><span class="keyword">function</span> <span class="title">show</span><span class="params">()</span></span>&#123;</div><div class="line">	<span class="keyword">echo</span> <span class="keyword">$this</span>-&gt;name,<span class="string">'&lt;br&gt;'</span>;</div><div class="line">	&#125;</div><div class="line">	<span class="keyword">public</span> <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">test</span><span class="params">()</span></span>&#123;</div><div class="line">	<span class="keyword">echo</span> <span class="string">'i am a boy!&lt;br&gt;'</span>;</div><div class="line">	&#125;</div><div class="line">&#125;</div><div class="line">$reflection = <span class="keyword">new</span> ReflectionClass(<span class="string">'Student'</span>);<span class="comment">//反射Student类的信息</span></div><div class="line">$stu = $reflection-&gt;new Instance(<span class="string">'tom'</span>);<span class="comment">//实例化Student对象，并传递参数</span></div><div class="line">$method = <span class="keyword">new</span> ReflectionMethod(<span class="string">'Student'</span>,<span class="string">'show'</span>);<span class="comment">//获取关于show()方法的信息</span></div><div class="line">$method-&gt;invoke($stu);<span class="comment">//方向代理调用</span></div><div class="line">$method = <span class="keyword">new</span> Reflection(<span class="string">'Student'</span>,<span class="string">'test'</span>);</div><div class="line">$method-&gt;invoke(<span class="keyword">NULL</span>);</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
</li>
</ol>
<blockquote>
<p>反射是为了了解系统类或不知道内部结构的类而使用</p>
</blockquote>
<h1 id="PDO"><a href="#PDO" class="headerlink" title="PDO"></a>PDO</h1><h2 id="连接MySQL的方法"><a href="#连接MySQL的方法" class="headerlink" title="连接MySQL的方法"></a>连接MySQL的方法</h2><p>方法一：<code>mysql_*组</code> 开启<code>extension = php_mysql.dll</code>扩展<br><code>mysql_connect(&#39;localhost&#39;,&#39;root&#39;,&#39;aa&#39;);</code>  //链接<br>方法二：<code>mysqli_*组</code>开启<code>extension = php_mysqli.dll</code>扩展<br><code>$link = mysqli_connect(&#39;localhost&#39;,&#39;root&#39;,&#39;aa&#39;,&#39;data&#39;);</code></p>
<blockquote>
<p>mysqli是mysql的升级版</p>
</blockquote>
<h2 id="PDO简介"><a href="#PDO简介" class="headerlink" title="PDO简介"></a>PDO简介</h2><p>PDO（PHP data object） PHP数据对象,PDO也是PHP内置的一组类（有三个），在与PDO相关的三个类中提供了一组访问数据库的轻量级，一致性的接口，无论使用什么数据库，都可以通过一致性的接口。操作数据库。<br>PDO是PHP5以上才支持的特性<br>开启相应拓展<code>extension =  php_pdo_xxx.dll</code></p>
<h2 id="PDO的核心类：PDO、PDOStatement、PDOException"><a href="#PDO的核心类：PDO、PDOStatement、PDOException" class="headerlink" title="PDO的核心类：PDO、PDOStatement、PDOException"></a>PDO的核心类：PDO、PDOStatement、PDOException</h2><ol>
<li>PDO：表示PHP程序和数据库直接的一个连接</li>
<li>PDOStatement：表示一条SQL处理语句，在该语句执行完成时，会返回执行结果</li>
<li>PDOException：表示PDO产生的异常<h2 id="实例化PDO对象"><a href="#实例化PDO对象" class="headerlink" title="实例化PDO对象"></a>实例化PDO对象</h2><h3 id="dsn-data-source-name-数据源名称"><a href="#dsn-data-source-name-数据源名称" class="headerlink" title="(dsn data source name) 数据源名称"></a>(dsn data source name) 数据源名称</h3>dsn 的组成结构：<code>$dsn = 数据库类型:host=主机地址;port=端口号;dbname=数据库;charset=字符编码;</code><br>语法：<code>$pdo = new PDO($dsn,数据库用户名,数据库密码);</code><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">$dsn = &apos;mysql:host=127.0.0.1;port=3306;dbname=php6;charset=utf8&apos;;</div><div class="line">$pdo = new PDO($dsn,&apos;root&apos;,&apos;aa&apos;);</div><div class="line">var_dump($pdo);</div></pre></td></tr></table></figure>
</li>
</ol>
<blockquote>
<p>本地主机可以省略，端口号是默认值时可以省略，dbname也是可以省略的，如果dbname省略，表示连接上服务器当时没有选择数据库。<br>但是数据库类型(<code>mysql:</code>)不可以省略<br><strong><em>数据库类型必须小写</em></strong></p>
</blockquote>
<h2 id="使用PDO对象"><a href="#使用PDO对象" class="headerlink" title="使用PDO对象"></a>使用PDO对象</h2><p>$pdo-&gt;exec();执行数据操作语句，执行成功返回受影响的记录数，否则返回false；<br>$pdo-&gt;query();//数据查询语句，返回PDOStatement对象</p>
<h3 id="操作数据"><a href="#操作数据" class="headerlink" title="操作数据"></a>操作数据</h3><figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line">$dsn = <span class="string">"mysql:host=127.0.0.1;port=3306;dbname=php06;charset=utf8"</span>;</div><div class="line">$pdo = <span class="keyword">new</span> PDO($dsn,<span class="string">'root'</span>,<span class="string">'aa'</span>);</div><div class="line">$sql = <span class="string">"insert into admin values(2,'aa','aa',0,0)"</span>;</div><div class="line">$rs = $pdo-&gt;exec($sql);</div><div class="line"><span class="keyword">if</span>($rs)</div><div class="line">	<span class="keyword">echo</span> <span class="string">'插入成功&lt;br&gt;生成的编号是：'</span>.$pdo-&gt;lastInsertId();</div><div class="line"><span class="keyword">elseif</span>($rs===<span class="number">0</span>)</div><div class="line">	<span class="keyword">echo</span> <span class="string">'没有数据变化'</span>;</div><div class="line"><span class="keyword">elseif</span>($rs===<span class="keyword">false</span>)&#123;</div><div class="line">	<span class="keyword">echo</span> <span class="string">'SQL语句执行失败'</span>;</div><div class="line">	$error = $pdo-&gt;errorInfo();</div><div class="line">	<span class="keyword">echo</span> <span class="string">'错误码：'</span>.$pdo-&gt;errorCode(),<span class="string">'&lt;br&gt;'</span>;</div><div class="line">	<span class="keyword">echo</span> <span class="string">'错误信息：'</span>.$error[<span class="number">2</span>];</div><div class="line">&#125;</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<h3 id="查询数据"><a href="#查询数据" class="headerlink" title="查询数据"></a>查询数据</h3><figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line">$dsn = <span class="string">'mysqy:host=127.0.0.1;port=3306;dbname=php06;charset=utf8'</span>;</div><div class="line">$pdo = <span class="keyword">new</span> PDO($dsn,<span class="string">'root'</span>,<span class="string">'aa'</span>);</div><div class="line">$sql = <span class="string">"select * from admin"</span>;</div><div class="line">$stmt = $pdo-&gt;query($sql);<span class="comment">//返回PDOStatement对象</span></div><div class="line"><span class="comment">//数据输出,array();</span></div><div class="line">$rows = $stmt-&gt;fetch();</div><div class="line">$rows = $stmt-&gt;fetch(PDO::FETCH_BOTH);<span class="comment">//同上</span></div><div class="line">$rows = $stmt-&gt;fetch(PDO::FETCH_ASSOC);<span class="comment">//匹配成关联数组</span></div><div class="line">$rows = $stmt-&gt;fetch(PDO::FETCH_NUM);<span class="comment">//匹配成索引数组</span></div><div class="line">$rows = $stmt-&gt;fetch(PDO::FETCH_OBJ);<span class="comment">//匹配成对象</span></div><div class="line"><span class="comment">/*************************************/</span></div><div class="line">$rs = $stmt-&gt;fetchALL();<span class="comment">//匹配所有数据</span></div><div class="line">$rs = $stmt-&gt;fetchALL(PDO::FETCH_ASSOC);<span class="comment">//匹配所有数据为关联数组</span></div><div class="line"><span class="comment">/*************************************/</span></div><div class="line"><span class="keyword">echo</span> $stmt-&gt;rowCount(),<span class="string">'&lt;br&gt;'</span>;<span class="comment">//获取总行数</span></div><div class="line"><span class="keyword">echo</span> $stmt-&gt;columnCount(),<span class="string">'&lt;br&gt;'</span>;<span class="comment">//获取总列数</span></div><div class="line"><span class="comment">/*************************************/</span></div><div class="line"><span class="comment">//获取一条数据，匹配成类的对象</span></div><div class="line">$obj = $stmt-&gt;fetchObject();</div><div class="line">var_dump($obj);<span class="comment">//PHP顶级父类stdClass类</span></div><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">Person</span></span>&#123;&#125;</div><div class="line">$obj = $stmt-&gt;fetchObject(<span class="string">'Person'</span>);</div><div class="line"><span class="comment">/*************************************/</span></div><div class="line">$col = $stmt-&gt;fetchColumn();<span class="comment">//匹配某一行的第0列</span></div><div class="line">$col = $stmt-&gt;fetchCOlumn(<span class="number">1</span>);<span class="comment">//匹配某一行的第1列</span></div><div class="line"><span class="comment">/*************************************/</span></div><div class="line"><span class="comment">//将列绑定到变量上，绑定列的时候，列的编号是从1开始</span></div><div class="line">$stmt-&gt;bindColumn(<span class="number">1</span>,$id);<span class="comment">//将第一列绑定到$id变量上</span></div><div class="line">$stmt-&gt;bindColumn(<span class="number">2</span>,$admin);<span class="comment">//bindColumn('admin',$admin);将admin列绑定到$admin变量上</span></div><div class="line">$stmt-&gt;fetch();</div><div class="line"><span class="keyword">echo</span> $id,<span class="string">'-'</span>,$admin;</div><div class="line">$stmt-&gt;fetch();</div><div class="line"><span class="keyword">echo</span> $id,<span class="string">'-'</span>,$admin;</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<blockquote>
<p>以上测试，均为单行或单模块测试。其它位注释状态</p>
</blockquote>
<p>脚下留心</p>
<blockquote>
<p>可以通过列的索引和列的名称来绑定到变量上<br>绑定列和变量的时候，列的索引从1开始</p>
</blockquote>
<h3 id="取出全部数据"><a href="#取出全部数据" class="headerlink" title="取出全部数据"></a>取出全部数据</h3><figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line"><span class="comment">//通过循环获取所以数据</span></div><div class="line"><span class="keyword">while</span>($rows = $stmt-&gt;fetch(PDO::FETCH_ASSOC))&#123;</div><div class="line">	<span class="keyword">echo</span> $rows[<span class="string">'id'</span>],<span class="string">'-'</span>,$rows[<span class="string">'admin'</span>],<span class="string">'&lt;br&gt;'</span>;</div><div class="line">&#125;</div><div class="line"><span class="comment">//通过内置迭代器遍历</span></div><div class="line"><span class="keyword">foreach</span>($stmt <span class="keyword">as</span> $rows)&#123;</div><div class="line">	<span class="keyword">echo</span> $rows[<span class="string">'id'</span>],<span class="string">'-'</span>,$rows[<span class="string">'admin'</span>],<span class="string">'&lt;br&gt;'</span>;</div><div class="line">&#125;</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<h3 id="PDO事物处理"><a href="#PDO事物处理" class="headerlink" title="PDO事物处理"></a>PDO事物处理</h3><figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line">$pdo-&gt;beginTransaction();<span class="comment">//开启事务模式</span></div><div class="line"><span class="keyword">echo</span> $pdo-&gt;exec(<span class="string">"insert into admin values(null,'11','11',0,0)"</span>);</div><div class="line"><span class="keyword">echo</span> $pdo-&gt;lastInsertId();</div><div class="line">$pdo-&gt;rollBack(); <span class="comment">//回滚事务</span></div><div class="line">$pdo-&gt;commit();<span class="comment">//提交事务</span></div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<h3 id="预处理语句"><a href="#预处理语句" class="headerlink" title="预处理语句"></a>预处理语句</h3><figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line">$sql = <span class="string">"insert into admin values(null,?,?,0,0)"</span>;<span class="comment">//?是占位符</span></div><div class="line">$stmt = $pdo-&gt;prepare($sql);<span class="comment">//返回PDOStatement对象</span></div><div class="line"><span class="comment">//执行预处理语句</span></div><div class="line">$stu = <span class="keyword">array</span>(</div><div class="line">	<span class="keyword">array</span>(<span class="string">'aa'</span>,<span class="string">'aa'</span>),</div><div class="line">	<span class="keyword">array</span>(<span class="string">'bb'</span>,<span class="string">'bb'</span>)</div><div class="line">);</div><div class="line"><span class="comment">/**********************************/</span></div><div class="line"><span class="comment">//绑定参数并执行（方法一）</span></div><div class="line"><span class="keyword">foreach</span>($stu <span class="keyword">as</span> $s)&#123;</div><div class="line">	$stmt-&gt;bindValue(<span class="number">1</span>,$s[<span class="number">0</span>]);</div><div class="line">	$stmt-&gt;bindValue(<span class="number">2</span>,$s[<span class="number">1</span>]);</div><div class="line">	$stmt-&gt;execute();<span class="comment">//返回bool值</span></div><div class="line">&#125;</div><div class="line"><span class="comment">/**********************************/</span></div><div class="line"><span class="comment">//绑定参数并执行（方法二）</span></div><div class="line"><span class="keyword">foreach</span>($stu <span class="keyword">as</span> $s)&#123;</div><div class="line">	$stmt-&gt;bindParam(<span class="number">1</span>,$s[<span class="number">0</span>]);</div><div class="line">	$stmt-&gt;bindParam(<span class="number">2</span>,$s[<span class="number">1</span>]);</div><div class="line">	$stmt-&gt;execute();<span class="comment">//返回bool值</span></div><div class="line">	</div><div class="line">&#125;</div><div class="line"><span class="comment">/**********************************/</span></div><div class="line"><span class="comment">//绑定参数并执行（方法三）</span></div><div class="line"><span class="keyword">foreach</span>($stu <span class="keyword">as</span> $s)&#123;</div><div class="line">	$stmt-&gt;execute($s);<span class="comment">//返回bool值</span></div><div class="line">&#125;</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<blockquote>
<p>词法分析—&gt;语法分析-&gt;编译-&gt;执行<br>如果一个sql语句要被多次执行，词法分析、语法分析、编译会多次执行，这样效率低下。<br>使用预处理语句，对预处理语句编译后传递不同的参数即可。</p>
</blockquote>
<p>bindParam 与 bindValue 的区别</p>
<blockquote>
<p>bindParam第二个参数是取地址，所以只能传递变量<br>bindValue第二个参数可以传递值也可以传递变量</p>
</blockquote>
<p>直接给预处理传递数组的时候要注意</p>
<blockquote>
<p>数组中值的个数和顺序要和占位符的顺序一致</p>
</blockquote>
<h3 id="参数占位符"><a href="#参数占位符" class="headerlink" title="参数占位符"></a>参数占位符</h3><figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line">$sql = <span class="string">"insert into admin values(null,:p1,:p2,0,0)"</span>;<span class="comment">//参数占位符</span></div><div class="line">$stmt-&gt;$pdo-&gt;prepare($sql)<span class="comment">//预处理语句</span></div><div class="line"><span class="comment">//执行预处理语句</span></div><div class="line">$stu = <span class="keyword">array</span>(</div><div class="line">	<span class="keyword">array</span>(<span class="string">'aa'</span>,<span class="string">'aa'</span>),</div><div class="line">	<span class="keyword">array</span>(<span class="string">'bb'</span>,<span class="string">'bb'</span>)<span class="number">8</span></div><div class="line">);</div><div class="line"><span class="keyword">foreach</span>($stu <span class="keyword">as</span> $s)&#123;</div><div class="line">	$stmt-&gt;bindParam(<span class="string">':p1'</span>,$s[<span class="number">0</span>]);</div><div class="line">	$stmt-&gt;bindParam(<span class="string">':p2'</span>,$s[<span class="number">1</span>]);</div><div class="line">	$stmt-&gt;execute();</div><div class="line">&#125;</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<h3 id="PDO-属性"><a href="#PDO-属性" class="headerlink" title="PDO 属性"></a>PDO 属性</h3><p><code>$pdo-&gt;setAttribute(键,值)；//设置PDO属性</code><br><code>$pdo-&gt;getAttribute(键,值)；//获取PDO属性</code><br><figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line">$dsn = <span class="string">'mysql:dbname=php6'</span>;</div><div class="line">$pdo = <span class="keyword">new</span> PDO($dsn,<span class="string">'root'</span>,<span class="string">'aa'</span>);</div><div class="line"></div><div class="line"><span class="keyword">echo</span> $pdo-&gt;getAttribute(PDO::ATTR_AUTOCOMMIT);<span class="comment">//自动提交 </span></div><div class="line">$pdo-&gt;setAttribute(PDO::ATTR_CASE,PDO::CASE::UPPER);<span class="comment">//强制将列明转换为大写</span></div><div class="line">$pdo-&gt;setAttribute(PDO::ATTR_ERRORMODE,PDO::ERRMODE_WARNING);<span class="comment">//错误报告为警告模式</span></div><div class="line"></div><div class="line">$stmt = $pdo-&gt;query(<span class="string">'select * from admin'</span>);</div><div class="line">$rows = $stmt-&gt;fetch(PDO::FETCH_ASSOC);</div><div class="line"><span class="keyword">echo</span> <span class="string">'&lt;pre&gt;'</span>;</div><div class="line">var_dump($rows);</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure></p>
<h3 id="PDO异常抛出"><a href="#PDO异常抛出" class="headerlink" title="PDO异常抛出"></a>PDO异常抛出</h3><p>PDO 会自动抛出异常<br><figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line"><span class="keyword">try</span>&#123;</div><div class="line">	$dsn = <span class="string">'mysql:dbname=php6'</span>;</div><div class="line">	$pdo = <span class="keyword">new</span> PDO($dsn,<span class="string">'root'</span>,<span class="string">'aa'</span>);<span class="comment">//PDO会自动抛出异常</span></div><div class="line">	$pdo -&gt; setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);<span class="comment">//有错误就抛出异常</span></div><div class="line">	$stmt = $pdo-&gt;query(<span class="string">'select * from admin'</span>);</div><div class="line">	var_dump($Stmt-fetch());</div><div class="line">	$age =<span class="number">60</span>;</div><div class="line">	<span class="keyword">if</span>($age&gt;<span class="number">30</span>)</div><div class="line">		<span class="keyword">throw</span> <span class="keyword">new</span> PDOException(<span class="string">'年龄不能超过30'</span>);</div><div class="line">&#125;<span class="keyword">catch</span>(PDOException $e)&#123;</div><div class="line">	<span class="keyword">echo</span> <span class="string">'错误信息：'</span>.$e-&gt;getmessage(),<span class="string">'&lt;br&gt;'</span>;</div><div class="line">	<span class="keyword">echo</span> <span class="string">'错误行号：'</span>.$e-&gt;getLine(),<span class="string">'&lt;br&gt;'</span>;</div><div class="line">&#125;</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure></p>
<h2 id="单例模式实现MyPDO类的封装"><a href="#单例模式实现MyPDO类的封装" class="headerlink" title="单例模式实现MyPDO类的封装"></a>单例模式实现MyPDO类的封装</h2><figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyPDO</span></span>&#123;</div><div class="line">    <span class="keyword">private</span> $type;<span class="comment">//数据库类型</span></div><div class="line">    <span class="keyword">private</span> $host;<span class="comment">//主机地址</span></div><div class="line">    <span class="keyword">private</span> $port;<span class="comment">//端口号</span></div><div class="line">    <span class="keyword">private</span> $dbname;<span class="comment">//数据库名</span></div><div class="line">    <span class="keyword">private</span> $charset;<span class="comment">//字符编码</span></div><div class="line">    <span class="keyword">private</span> $user;<span class="comment">//数据库用户名</span></div><div class="line">    <span class="keyword">private</span> $pwd;<span class="comment">//数据库密码</span></div><div class="line">    <span class="keyword">private</span> $pdo;<span class="comment">//PDO对象</span></div><div class="line">    <span class="keyword">private</span> <span class="keyword">static</span> $instance;<span class="comment">//当前类的实例</span></div><div class="line">    <span class="comment">//使用的构造函数用来阻止在类的外部实例化</span></div><div class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">function</span> <span class="title">__construct</span><span class="params">($param)</span></span>&#123;</div><div class="line">        <span class="keyword">$this</span>-&gt;initParam($param);</div><div class="line">        <span class="keyword">$this</span>-&gt;initPDO();</div><div class="line">    &#125;</div><div class="line">    <span class="comment">//私有的__clone()用来阻止在类的外部克隆对象</span></div><div class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">function</span> <span class="title">__clone</span><span class="params">()</span></span>&#123;&#125;</div><div class="line">    <span class="comment">//公有的静态方法用来获取当前类的实例</span></div><div class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">getInstance</span><span class="params">($param=array<span class="params">()</span>)</span></span>&#123;</div><div class="line">        <span class="keyword">if</span>(!<span class="keyword">self</span>::$instance <span class="keyword">instanceof</span> <span class="keyword">self</span>)</div><div class="line">            <span class="keyword">self</span>::$instance = <span class="keyword">new</span> <span class="keyword">self</span>($param);</div><div class="line">        <span class="keyword">return</span> <span class="keyword">self</span>::$instance;</div><div class="line">    &#125;</div><div class="line">    <span class="comment">//初始化成员变量</span></div><div class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">function</span> <span class="title">initParam</span><span class="params">($param)</span></span>&#123;</div><div class="line">        <span class="keyword">$this</span>-&gt;type = <span class="keyword">isset</span>($param[<span class="string">'type'</span>])?$param[<span class="string">'type'</span>]:<span class="string">'mysql'</span>;</div><div class="line">        <span class="keyword">$this</span>-&gt;host = <span class="keyword">isset</span>($param[<span class="string">'host'</span>])?$param[<span class="string">'host'</span>]:<span class="string">'localhost'</span>;</div><div class="line">        <span class="keyword">$this</span>-&gt;port = <span class="keyword">isset</span>($param[<span class="string">'port'</span>])?$param[<span class="string">'port'</span>]:<span class="string">'3306'</span>;</div><div class="line">        <span class="keyword">$this</span>-&gt;dbname = <span class="keyword">isset</span>($param[<span class="string">'dbname'</span>])?$param[<span class="string">'dbname'</span>]:<span class="string">'uiste'</span>;</div><div class="line">        <span class="keyword">$this</span>-&gt;charset = <span class="keyword">isset</span>($param[<span class="string">'charset'</span>])?$param[<span class="string">'charset'</span>]:<span class="string">'utf8'</span>;</div><div class="line">        <span class="keyword">$this</span>-&gt;user = <span class="keyword">isset</span>($param[<span class="string">'user'</span>])?$param[<span class="string">'user'</span>]:<span class="string">'root'</span>;</div><div class="line">        <span class="keyword">$this</span>-&gt;pwd = <span class="keyword">isset</span>($param[<span class="string">'pwd'</span>])?$param[<span class="string">'pwd'</span>]:<span class="string">'123456'</span>;</div><div class="line">    &#125;</div><div class="line">    <span class="comment">//创建PDO对象</span></div><div class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">function</span> <span class="title">initPDO</span><span class="params">()</span></span>&#123;</div><div class="line">        $dsn = <span class="string">"&#123;$this-&gt;type&#125;:host=&#123;$this-&gt;host&#125;;port=&#123;$this-&gt;port&#125;;dbname=&#123;$this-&gt;dbname&#125;;charset=&#123;$this-&gt;charset&#125;"</span>;</div><div class="line">        <span class="keyword">$this</span>-&gt;pdo = <span class="keyword">new</span> PDO($dsn,<span class="keyword">$this</span>-&gt;user,<span class="keyword">$this</span>-&gt;pwd);</div><div class="line">    &#125;</div><div class="line">    <span class="comment">//执行sql语句,返回PDOStatement对象</span></div><div class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">function</span> <span class="title">getPDOStatement</span><span class="params">($sql)</span></span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="keyword">$this</span>-&gt;pdo-&gt;query($sql);</div><div class="line">    &#125;</div><div class="line">    <span class="comment">//判断匹配的类型</span></div><div class="line">    <span class="keyword">private</span> <span class="function"><span class="keyword">function</span> <span class="title">getFetchType</span><span class="params">($type)</span></span>&#123;</div><div class="line">        $allow_type = <span class="keyword">array</span>(<span class="string">'assoc'</span>,<span class="string">'num'</span>,<span class="string">'both'</span>);</div><div class="line">        <span class="keyword">if</span>(!in_array($type,$allow_type))</div><div class="line">            $type=<span class="string">'assoc'</span>;</div><div class="line">        <span class="keyword">switch</span>($type)&#123;</div><div class="line">            <span class="keyword">case</span> <span class="string">'assoc'</span>:</div><div class="line">                <span class="keyword">return</span> PDO::FETCH_ASSOC;</div><div class="line">            <span class="keyword">case</span> <span class="string">'num'</span>:</div><div class="line">                <span class="keyword">return</span> PDO::FETCH_NUM;</div><div class="line">            <span class="keyword">case</span> <span class="string">'both'</span>:</div><div class="line">                <span class="keyword">return</span> PDO::FETCH_BOTH;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">    <span class="comment">//获取所有记录，返回二位数组</span></div><div class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">getAll</span><span class="params">($sql,$type=<span class="string">'assoc'</span>)</span></span>&#123;</div><div class="line">        $stmt = <span class="keyword">$this</span>-&gt;getPDOStatement($sql);</div><div class="line">        $fetch_type = <span class="keyword">$this</span>-&gt;getFetchType($type);</div><div class="line">        <span class="keyword">return</span> $stmt-&gt;fetchAll($fetch_type);</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">getOne</span><span class="params">($sql,$type=<span class="string">'assoc'</span>)</span></span>&#123;</div><div class="line">        $stmt = <span class="keyword">$this</span>-&gt;getPDOStatement($sql);</div><div class="line">        $fetch_type = <span class="keyword">$this</span>-&gt;getFetchType($type);</div><div class="line">        <span class="keyword">return</span> $stmt-&gt;fetchAll($fetch_type);</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">getColumn</span><span class="params">($sql)</span></span>&#123;</div><div class="line">        $stmt = <span class="keyword">$this</span>-&gt;getPDOStatement($sql);</div><div class="line">        <span class="keyword">return</span> $stmt-&gt;fetColumn();</div><div class="line">    &#125;</div><div class="line">    <span class="comment">//数据库增、删、改,返回受影响的行数</span></div><div class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">exec</span><span class="params">($sql)</span></span>&#123;</div><div class="line">        $result = <span class="keyword">$this</span>-&gt;pdo-&gt;exec($sql);</div><div class="line">        <span class="keyword">if</span>(<span class="keyword">false</span>!==$result)</div><div class="line">            <span class="keyword">return</span> $result;</div><div class="line">        <span class="keyword">else</span>&#123;</div><div class="line">        	$errorinfo_arr = <span class="keyword">$this</span>-&gt;pdo-&gt;errorInfo();</div><div class="line">            <span class="keyword">echo</span> <span class="string">'SQL 语句执行失败&lt;br&gt;'</span>;</div><div class="line">            <span class="keyword">echo</span> <span class="string">'Error SQL：'</span>.$sql.<span class="string">'&lt;br&gt;'</span>;</div><div class="line">            <span class="keyword">echo</span> <span class="string">'SQLSTATE error code：'</span>.$errorinfo_arr[<span class="number">0</span>].<span class="string">'&lt;br&gt;'</span>;</div><div class="line">            <span class="keyword">echo</span> <span class="string">'Driver-specific error code：'</span>.$errorinfo_arr[<span class="number">1</span>].<span class="string">'&lt;br&gt;'</span>;</div><div class="line">            <span class="keyword">echo</span> <span class="string">'Driver-specific error message：'</span>.$errorinfo_arr[<span class="number">2</span>].<span class="string">'&lt;br&gt;'</span>;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<hr>
<ol>
<li>PDO的作用<br>PHP数据对象，内置的一组类（有三个），在与PDO相关的三个类中提供了一组访问数据库的轻量级，一致性的接口，无论使用什么数据库，都可以通过一致性的接口，操作数据库。</li>
<li>PDO的加载<br>PDO是PHP5以上才支持的特性<br>需要开启相应拓展<code>extension =  php_pdo_xxx.dll</code></li>
<li>PDO技术中的PDO对象<br>dsn 的组成结构：<code>$dsn = 数据库类型:host=主机地址;port=端口号;dbname=数据库;charset=字符编码;</code><br>语法：<code>$pdo = new PDO($dsn,数据库用户名,数据库密码);</code></li>
<li>PDO技术中的PDOStatement对象<br>代表一条预处理语句，并在该语句被执行后代表一个相关的结果集。<br><code>PDOStatement::bindColumn</code> — 绑定一列到一个 PHP 变量<br><code>PDOStatement::bindParam</code> — 绑定一个参数到指定的变量名<br><code>PDOStatement::bindValue</code> — 把一个值绑定到一个参数<br><code>PDOStatement::closeCursor</code> — 关闭游标，使语句能再次被执行。<br><code>PDOStatement::columnCount</code> — 返回结果集中的列数<br><code>PDOStatement::debugDumpParams</code> — 打印一条 SQL 预处理命令<br><code>PDOStatement::errorCode</code> — 获取跟上一次语句句柄操作相关的 SQLSTATE<br><code>PDOStatement::errorInfo</code> — 获取跟上一次语句句柄操作相关的扩展错误信息<br><code>PDOStatement::execute</code> — 执行一条预处理语句<br><code>PDOStatement::fetch</code> — 从结果集中获取下一行<br><code>PDOStatement::fetchAll</code> — 返回一个包含结果集中所有行的数组<br><code>PDOStatement::fetchColumn</code> — 从结果集中的下一行返回单独的一列。<br><code>PDOStatement::fetchObject</code> — 获取下一行并作为一个对象返回。<br><code>PDOStatement::getAttribute</code> — 检索一个语句属性<br><code>PDOStatement::getColumnMeta</code> — 返回结果集中一列的元数据<br><code>PDOStatement::nextRowset</code> — 在一个多行集语句句柄中推进到下一个行集<br><code>PDOStatement::rowCount</code> — 返回受上一个 SQL 语句影响的行数<br><code>PDOStatement::setAttribute</code> — 设置一个语句属性<br><code>PDOStatement::setFetchMode</code> — 为语句设置默认的获取模式。</li>
<li>PDO技术中的PDOException对象<br>代表一个由 PDO 产生的错误。在自己的代码不应抛出一个 PDOException 异常</li>
<li>PDO的操作——插入操作<br>$pdo-&gt;exec();   //执行数据操作语句，执行成功返回受影响的记录数，否则返回false。</li>
<li>掌握PDO的操作——写操作<br>？？？</li>
<li>掌握PDO的操作——查询操作<br>$pdo-&gt;query();  //数据查询语句，返回PDOStatement对象</li>
<li>掌握PDO的事务操作<br>$pdo-&gt;beginTransaction(); //开启事务<br>$pdo-&gt;rollBack(); //回滚事务<br>$pdo-&gt;commit();//提交事务</li>
<li>掌握PDO的预处理</li>
</ol>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line">$dsn=<span class="string">'mysql:host=localhost;port=3306;dbname=php6;charset=utf8'</span>;</div><div class="line">$pdo=<span class="keyword">new</span> PDO($dsn,<span class="string">'root'</span>,<span class="string">'aa'</span>);</div><div class="line"><span class="comment">//预处理语句</span></div><div class="line">$sql=<span class="string">"insert into admin values (null,?,?,0,0)"</span>; <span class="comment">//?是占位符</span></div><div class="line">$stmt=$pdo-&gt;prepare($sql);  <span class="comment">//返回PDOStatement对象</span></div><div class="line"><span class="comment">//执行预处理语句</span></div><div class="line">$stu=<span class="keyword">array</span>(</div><div class="line">    <span class="keyword">array</span>(<span class="string">'aa'</span>,<span class="string">'aa'</span>),</div><div class="line">    <span class="keyword">array</span>(<span class="string">'bb'</span>,<span class="string">'bb'</span>)</div><div class="line">);</div><div class="line"><span class="comment">//绑定参数并执行（方法一）</span></div><div class="line"><span class="comment">/*</span></div><div class="line">foreach($stu as $s)&#123;</div><div class="line">    $stmt-&gt;bindValue(1, $s[0]);</div><div class="line">    $stmt-&gt;bindValue(2, $s[1]);</div><div class="line">    $stmt-&gt;execute();   //返回bool值</div><div class="line">&#125;</div><div class="line"> */</div><div class="line"><span class="comment">//绑定参数并执行（方法二）</span></div><div class="line"><span class="comment">/*</span></div><div class="line">foreach($stu as $s)&#123;</div><div class="line">    $stmt-&gt;bindParam(1, $s[0]);</div><div class="line">    $stmt-&gt;bindParam(2, $s[1]);</div><div class="line">    $stmt-&gt;execute();   //返回bool值</div><div class="line">&#125;</div><div class="line"> */</div><div class="line"><span class="comment">//绑定参数并执行（方法三）,直接传递数组</span></div><div class="line"><span class="keyword">foreach</span>($stu <span class="keyword">as</span> $s)&#123;</div><div class="line">    $stmt-&gt;execute($s);   <span class="comment">//返回bool值</span></div><div class="line">&#125;</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">$sql=<span class="string">"insert into admin values (null,:p1,:p2,0,0)"</span>; <span class="comment">//参数占位符</span></div><div class="line"><span class="keyword">foreach</span> ($stu <span class="keyword">as</span> $s)&#123;</div><div class="line">    $stmt-&gt;bindParam(<span class="string">':p1'</span>, $s[<span class="number">0</span>]); <span class="comment">//绑定参数</span></div><div class="line">    $stmt-&gt;bindParam(<span class="string">':p2'</span>, $s[<span class="number">1</span>]);</div><div class="line">    $stmt-&gt;execute();</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<ol>
<li>PDO的属性操作<br>$pdo-&gt;getAttribute(键)：获取PDO属性<br>$pdo-&gt;getAttribute(键)：获取PDO属性</li>
<li>PDO的异常处理机制<br>PDO会自动抛出异常，其他的地方不能自动抛出<br>$pdo-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);设置为自动抛出异常</li>
</ol>
<h1 id="总"><a href="#总" class="headerlink" title="总"></a>总</h1><p>反射：获取类中方法、属性、参数、注释等封闭信息的方法<br>发射的父类（reflection）<br>ReflectionClass:export()：反射出类的内部结构<br>getMethods()：获取所有方法、getProterties()：获取所有属性<br>getConstants()：获取常量<br>通过反射类可以创建代理类的对象  newInstance()<br>发射通过反向代理调用对象的方法<br>PDO（PHP data object）提供了一组一致性的接口，用来访问不同的数据库。<br>要使用pdo之前必须开启pdo扩展<br>PDO核心类<br>PDO：表示PHP和数据库的链接对象<br>PDOStatement类，PDO执行sql语句返回的结果<br>PDOException：PDO异常<br>实例化PDO:<br>$dsn=’mysql:host=主机;port=端口号;dbname=数据库名;charset=字符编码’<br>PDO($dsn,用户名,密码)<br>脚下留心：数据类型要小写<br>使用PDO<br>$pdo-&gt;exec()：执行数据操作语句，返回的受影响的记录数或false<br>$pdo-&gt;query()：执行数据查询语句，返回的是PDOStatement对象<br>$pdo-&gt;lastInsertId()：获取生成的id编号<br>获取PDOStatement对象中的数据<br>$pdo-&gt;fetch()：获取一条数据<br>$pdo-&gt;fetchAll()：获取所有数据<br>$pdo-&gt;fetchColumn()：获取列<br>$pdo-&gt;fetchObject()：获取一行数据，并匹配成对象<br>$pdo-&gt;rowCount()：总行数<br>$pdo-&gt;columnCount()：总列数<br>$pdo-&gt;bindColumn()：将列绑定到变量上<br>匹配的类型：<br>PDO::FETCH_BOTH<br>PDO::FETCH_ASSOC<br>PDO::FETCH_NUM<br>PDO事务<br>$pdo-&gt;beginTransaction()<br>$pdo-&gt;rollback()<br>$pdo-&gt;commit()<br>预处理<br>$pdo-&gt;prepare()<br>位置占位符（？）<br>参数占位符（:参数名）<br>绑定参数<br>bindValue()<br>bindParam()<br>操作数据<br>$pdo-&gt;getAttribute()<br>$pdo-&gt;setAttribute()<br>异常处理<br>默认情况下，如果有错误就报错，不会抛出异常，设置如下语句使得自动抛出异常：$pdo-&gt;setAttribute(PDO::ERRMODE,PDO::ERRMODE_EXCEPTION)</p>

          
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
  </section>

  
  <nav class="pagination">
    <span class="page-number current">1</span><a class="page-number" href="/page/2/">2</a><span class="space">&hellip;</span><a class="page-number" href="/page/14/">14</a><a class="extend next" rel="next" href="/page/2/"><i class="fa fa-angle-right"></i></a>
  </nav>



          </div>
          


          

        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      

      <section class="site-overview sidebar-panel  sidebar-panel-active ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.png"
               alt="uiste" />
          <p class="site-author-name" itemprop="name">uiste</p>
          <p class="site-description motion-element" itemprop="description">Stay Hungry，Stay Foolish</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">70</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              
                <span class="site-state-item-count">13</span>
                <span class="site-state-item-name">分类</span>
              
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">55</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/uiste" target="_blank" rel="external nofollow" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/uiste" target="_blank" rel="external nofollow" title="微博">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  微博
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.zhihu.com/people/uiste" target="_blank" rel="external nofollow" title="知乎">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  知乎
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              友情链接
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.uiste.com" title="uiste 个人博客" target="_blank">uiste 个人博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://uiste.github.io" title="uiste 技术博客" target="_blank">uiste 技术博客</a>
                </li>
              
            </ul>
          </div>
        

      </section>

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2015 - 
  <span itemprop="copyrightYear">2016</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">uiste</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="http://hexo.io" rel="external nofollow">Hexo</a> 趋势动力
</div>
<!--站长统计-->
<script src="https://s95.cnzz.com/z_stat.php?id=1259894121&web_id=1259894121" language="JavaScript"></script>
<!--<div class="theme-info">
  Theme -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next" rel="external nofollow">
    NexT.Mist
  </a>
</div> -->
&nbsp;&nbsp;&nbsp;本站总点击 <span id="busuanzi_value_site_pv"></span> 次
&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;您是第 <span id="busuanzi_value_site_uv"></span> 位访客

<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
</script>

<script>
(function(){
    var bp = document.createElement('script');
    bp.src = '//push.zhanzhang.baidu.com/push.js';
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  

  

  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"uiste"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
    <script src="/vendors/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>
    <script src="/js/src/hook-duoshuo.js"></script>
  






  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
       search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();

    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
    'use strict';
    $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
            // get the contents from search data
            isfetched = true;
            $('.popup').detach().appendTo('.header-inner');
            var datas = $( "entry", xmlResponse ).map(function() {
                return {
                    title: $( "title", this ).text(),
                    content: $("content",this).text(),
                    url: $( "url" , this).text()
                };
            }).get();
            var $input = document.getElementById(search_id);
            var $resultContent = document.getElementById(content_id);
            $input.addEventListener('input', function(){
                var matchcounts = 0;
                var str='<ul class=\"search-result-list\">';
                var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                $resultContent.innerHTML = "";
                if (this.value.trim().length > 1) {
                // perform local searching
                datas.forEach(function(data) {
                    var isMatch = true;
                    var content_index = [];
                    var data_title = data.title.trim().toLowerCase();
                    var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                    var data_url = data.url;
                    var index_title = -1;
                    var index_content = -1;
                    var first_occur = -1;
                    // only match artiles with not empty titles and contents
                    if(data_title != '' && data_content != '') {
                        keywords.forEach(function(keyword, i) {
                            index_title = data_title.indexOf(keyword);
                            index_content = data_content.indexOf(keyword);
                            if( index_title < 0 && index_content < 0 ){
                                isMatch = false;
                            } else {
                                if (index_content < 0) {
                                    index_content = 0;
                                }
                                if (i == 0) {
                                    first_occur = index_content;
                                }
                            }
                        });
                    }
                    // show search results
                    if (isMatch) {
                        matchcounts += 1;
                        str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                        var content = data.content.trim().replace(/<[^>]+>/g,"");
                        if (first_occur >= 0) {
                            // cut out 100 characters
                            var start = first_occur - 20;
                            var end = first_occur + 80;
                            if(start < 0){
                                start = 0;
                            }
                            if(start == 0){
                                end = 50;
                            }
                            if(end > content.length){
                                end = content.length;
                            }
                            var match_content = content.substring(start, end);
                            // highlight all keywords
                            keywords.forEach(function(keyword){
                                var regS = new RegExp(keyword, "gi");
                                match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                            });

                            str += "<p class=\"search-result\">" + match_content +"...</p>"
                        }
                        str += "</li>";
                    }
                })};
                str += "</ul>";
                if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
                if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
                $resultContent.innerHTML = str;
            });
            proceedsearch();
        }
    });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };

    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  

  

  

</body>
</html>
